<template>
  <div class="seckill-management">
    <div class="page-header">
      <h2>秒杀管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="秒杀名称">
          <el-input v-model="searchForm.seckillName" placeholder="请输入秒杀名称" clearable />
        </el-form-item>
        <el-form-item label="秒杀状态">
          <el-select v-model="searchForm.seckillState" placeholder="请选择状态" clearable>
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSeckills">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增秒杀
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="seckillList" v-loading="loading" stripe>
        <el-table-column prop="seckillId" label="秒杀ID" width="80" />
        <el-table-column prop="seckillName" label="秒杀名称" width="200" />
        <el-table-column prop="beforePrice" label="原价" width="120">
          <template #default="{ row }">
            <span class="price-original">¥{{ row.beforePrice?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="afterPrice" label="秒杀价" width="120">
          <template #default="{ row }">
            <span class="price-seckill">¥{{ row.afterPrice?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inventoryNum" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="row.inventoryNum > 10 ? 'success' : row.inventoryNum > 0 ? 'warning' : 'danger'">
              {{ row.inventoryNum || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="seckillState" label="秒杀状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getSeckillStateType(row.seckillState)">
              {{ getSeckillStateText(row.seckillState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editSeckill(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteSeckill(row.seckillId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑秒杀' : '新增秒杀'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="seckillForm" :rules="seckillRules" ref="seckillFormRef" label-width="100px">
        <el-form-item label="秒杀名称" prop="seckillName">
          <el-input v-model="seckillForm.seckillName" placeholder="请输入秒杀名称" />
        </el-form-item>
        <el-form-item label="原价" prop="beforePrice">
          <el-input-number v-model="seckillForm.beforePrice" :min="0" :precision="2" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="秒杀价" prop="afterPrice">
          <el-input-number v-model="seckillForm.afterPrice" :min="0" :precision="2" placeholder="请输入秒杀价" />
        </el-form-item>
        <el-form-item label="库存" prop="inventoryNum">
          <el-input-number v-model="seckillForm.inventoryNum" :min="0" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="秒杀状态" prop="seckillState">
          <el-select v-model="seckillForm.seckillState" placeholder="请选择状态">
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="seckillForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="seckillForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { seckillApi } from '@/api/seckill'

// 响应式数据
const loading = ref(false)
const seckillList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const seckillFormRef = ref()

// 搜索表单
const searchForm = reactive({
  seckillName: '',
  seckillState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 秒杀表单
const seckillForm = reactive({
  seckillId: null,
  seckillName: '',
  beforePrice: 0,
  afterPrice: 0,
  inventoryNum: 0,
  seckillState: 1,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const seckillRules = {
  seckillName: [
    { required: true, message: '请输入秒杀名称', trigger: 'blur' }
  ],
  beforePrice: [
    { required: true, message: '请输入原价', trigger: 'blur' }
  ],
  afterPrice: [
    { required: true, message: '请输入秒杀价', trigger: 'blur' }
  ],
  inventoryNum: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  seckillState: [
    { required: true, message: '请选择秒杀状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取秒杀状态文本
const getSeckillStateText = (state) => {
  const stateMap = {
    1: '进行中',
    2: '已终止'
  }
  return stateMap[state] || '未知'
}

// 获取秒杀状态标签类型
const getSeckillStateType = (state) => {
  const stateMap = {
    1: 'success',
    2: 'danger'
  }
  return stateMap[state] || 'info'
}

// 搜索秒杀
const searchSeckills = async () => {
  loading.value = true
  try {
    const response = await seckillApi.getSeckillList(searchForm)
    if (response.code === 200) {
      seckillList.value = response.data || []
      pagination.total = seckillList.value.length
    }
  } catch (error) {
    console.error('搜索秒杀失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    seckillName: '',
    seckillState: null
  })
  searchSeckills()
}

// 编辑秒杀
const editSeckill = (row) => {
  isEdit.value = true
  Object.assign(seckillForm, row)
  showAddDialog.value = true
}

// 删除秒杀
const deleteSeckill = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个秒杀活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await seckillApi.deleteSeckill(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchSeckills()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除秒杀失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await seckillFormRef.value.validate()

    const response = isEdit.value
      ? await seckillApi.updateSeckill(seckillForm)
      : await seckillApi.addSeckill(seckillForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchSeckills()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(seckillForm, {
    seckillId: null,
    seckillName: '',
    beforePrice: 0,
    afterPrice: 0,
    inventoryNum: 0,
    seckillState: 1,
    startTime: '',
    endTime: ''
  })
  isEdit.value = false
  seckillFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchSeckills()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchSeckills()
}

// 初始化
onMounted(() => {
  searchSeckills()
})
</script>

<style scoped>
.seckill-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.price-original {
  text-decoration: line-through;
  color: #999;
}

.price-seckill {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}
</style>